//
//  YWVideoView.m
//  videoTest3
//
//  Created by jun peng on 2022/6/7.
//

#import "YWVideoView.h"

#import <TXLiteAVSDK_Player/TXLiteAVSDK.h>



@interface YWVideoView ()

//保存是否静音（1、这个在朋友圈的话应该是保持静音的、2、去详情页才另外创建的播放界面才让它有声音、3、假如是汽车之家列表就是有个可控制是否静音的按钮（这按钮不需要VC来决定是否静音依然交给videoView来自己决定是否静音）、4、抖音列表就默认有声音）
@property (nonatomic, assign) BOOL mute;

@property(nonatomic,copy)NSString *urlString;


@property (weak, nonatomic) IBOutlet UIButton *loadingView;

@property (weak, nonatomic) IBOutlet UIView *videoFunctionView;

@property (weak, nonatomic) IBOutlet UIButton *bigScaleBtn;
- (IBAction)bigScaleBtnClick:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UIButton *playOrPauseBtn;
- (IBAction)playOrPauseBtnClick:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
- (IBAction)sliderValueChange;
- (IBAction)touchDownSlider;
- (IBAction)touchUpInsideSlider;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bigScaleBtnTrailingConstraint;

@end

@implementation YWVideoView


//创建videoPlayView
+ (instancetype)videoView{
    
    return [[[NSBundle mainBundle] loadNibNamed:@"YWVideoView" owner:nil options:nil] firstObject];
}

-(void)awakeFromNib{
    [super awakeFromNib];
    
    //单击手势控制toolView出现
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self addGestureRecognizer:tap];
    
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground) name:YWEnterBackgroundNote object:nil];
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)enterBackground{
    
    [self pausePlay];
    self.playOrPauseBtn.selected = NO;
    
}

-(void)setupUI{
    
    //先默认隐藏
    self.loadingView.hidden = YES;
    self.bigScaleBtn.hidden = YES;
    self.bigScaleBtnTrailingConstraint.constant = 0;
    self.videoFunctionView.hidden = YES;
    
    //添加loading动画
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 0.9;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    rotationAnimation.removedOnCompletion = NO;//这个属性才会重新出现界面时不会停止动画
    [self.loadingView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
   
    
    // 设置进度条的内容
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"进度条原点3"] forState:UIControlStateNormal];
    [self.progressSlider setMaximumTrackImage:[UIImage imageNamed:@"MaximumTrackImage"] forState:UIControlStateNormal];
    [self.progressSlider setMinimumTrackImage:[UIImage imageNamed:@"MinimumTrackImage"] forState:UIControlStateNormal];
    
    
    // 2、设置按钮的状态
    self.playOrPauseBtn.selected = NO;
    
    // 3、设置slider
    self.progressSlider.value = 0;
    
    // 4、设置两个时间label
    self.currentTimeLabel.text = @"00:00";
    
    self.totalTimeLabel.text = @"00:00";
    
}


-(void)setIsNeedBigBtn:(BOOL)isNeedBigBtn{
    _isNeedBigBtn = isNeedBigBtn;
    if (isNeedBigBtn == YES) {
        self.bigScaleBtn.hidden = NO;
        self.bigScaleBtnTrailingConstraint.constant = 15;
    }
    else{
        self.bigScaleBtn.hidden = YES;
        self.bigScaleBtnTrailingConstraint.constant = 0;
    }
    
}

-(void)setIsNeedToolBar:(BOOL)isNeedToolBar{
    _isNeedToolBar = isNeedToolBar;
    if (isNeedToolBar == YES) {
        self.videoFunctionView.hidden = NO;
    }
    else{
        self.videoFunctionView.hidden = YES;
    }
    
}

-(void)setIsNeedLoadingView:(BOOL)isNeedLoadingView{
    _isNeedLoadingView = isNeedLoadingView;
//    if (isNeedLoadingView == YES) {
//        self.loadingView.hidden = NO;
//    }
//    else{
//        self.loadingView.hidden = YES;
//    }
    
    
}



//单击
- (void)tapAction:(UITapGestureRecognizer *)sender {

    if ([self.delegate respondsToSelector:@selector(videoViewDidTap:)]) {
        [self.delegate videoViewDidTap:self];
    }
    
}


//开始
-(void)startPlayWithUrl:(NSString *)urlString withMute:(BOOL)mute{
    
    self.urlString = urlString;
    
    MJWeakSelf
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
  
      [playerManager startPlayWithUrl:urlString view:self complication:^{
          
          //重设是否要静音
//          weakSelf.mute = weakSelf.mute;
          
          //这里用在朋友圈列表、默认就是静音
          //是否静音这里应该是YES
          
          //因为列表VC和小视频详情VC都共用这个videoView、所以mute由外界提供
          weakSelf.mute = mute;
  
      } startPlay:^{
          
          weakSelf.loadingView.hidden = YES;
          
          if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidStartPlay:)]) {
              [weakSelf.delegate videoViewDidStartPlay:weakSelf];
          }
  
      } progress:^(float progress, float duration, float playable) {
  
          weakSelf.loadingView.hidden = YES;
          if (weakSelf.isPlaying) {
              weakSelf.playOrPauseBtn.selected = YES;
          }
          else{
              
              weakSelf.playOrPauseBtn.selected = NO;
              
          }
          
          weakSelf.progressSlider.value = progress / duration;
          
          weakSelf.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:duration];
          
          weakSelf.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:progress];
          
          
      } end:^{
  
      } loading:^{
          if (weakSelf.isNeedLoadingView) {
              weakSelf.loadingView.hidden = NO;
          }
          
      }];
    
}


-(void)continuePlayWithAnthorViewWithUrl:(NSString *)urlString WithMute:(BOOL)mute{
    
    
    self.urlString = urlString;
    
    MJWeakSelf
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    //继续播放
    [self continuePlay];
    
    
    [playerManager continuePlayWithAnthorView:self complication:^{
        
        weakSelf.mute = mute;
        
    } startPlay:^{
        weakSelf.loadingView.hidden = YES;
        if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidStartPlay:)]) {
            [weakSelf.delegate videoViewDidStartPlay:weakSelf];
        }
        
    } progress:^(float progress, float duration, float playable) {
        weakSelf.loadingView.hidden = YES;
        if (weakSelf.isPlaying) {
            weakSelf.playOrPauseBtn.selected = YES;
        }
        else{
            
            weakSelf.playOrPauseBtn.selected = NO;
            
        }
        
        weakSelf.progressSlider.value = progress / duration;
        
        weakSelf.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:duration];
        
        weakSelf.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:progress];
        
    } end:^{
        
    } loading:^{
        if (weakSelf.isNeedLoadingView) {
            weakSelf.loadingView.hidden = NO;
        }
    }];
    
  
    
}

//暂停
-(void)stopPlay{
    
    
    MJWeakSelf
    
        YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
        [playerManager stopPlayWithComplication:^{
            if ([weakSelf.delegate respondsToSelector:@selector(videoViewDidSotpPlay:)]) {
                [weakSelf.delegate videoViewDidSotpPlay:weakSelf];
            }
        }];
    
    
}



//暂停
-(void)pausePlay{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager pausePlayWithComplication:^{
        
    }];
    
}

//继续
-(void)continuePlay{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    [playerManager continuePlayWithComplication:^{
        
    }];
    
    
}





-(void)setMute:(BOOL)mute{
    _mute = mute;
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    [playerManager setMute:mute];
    
}

-(BOOL)isPlaying{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    return playerManager.currentVideoMessageModel.isPlaying;
}


- (void)snapshot:(void (^)(UIImage *))snapshotCompletionBlock{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    [playerManager snapshot:^(UIImage * _Nonnull image) {
        if (snapshotCompletionBlock) {
            snapshotCompletionBlock(image);
        }
    }];
    
}


- (IBAction)sliderValueChange{
    
    YWVideoPlayerManager *playerManager = [YWVideoPlayerManager sharevideoPlayerManager];
    
    // 更新时间label数据
    NSTimeInterval currentTime = playerManager.currentVideoMessageModel.totalTime * self.progressSlider.value;
    
    NSTimeInterval totalTime = playerManager.currentVideoMessageModel.totalTime;
    
    
    self.currentTimeLabel.text = [YWVideoPlayerManager stringWithTime:currentTime];
    
    self.totalTimeLabel.text = [YWVideoPlayerManager stringWithTime:totalTime];
    
    // 更新视频进度
    [playerManager seekToTime:currentTime];
}
- (IBAction)touchDownSlider{
    
    [self pausePlay];
    
}
- (IBAction)touchUpInsideSlider{
    [self continuePlay];
    
}

- (IBAction)playOrPauseBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        [self continuePlay];
    }
    else{
        [self pausePlay];
    }
}

- (IBAction)bigScaleBtnClick:(UIButton *)sender{
    
    
}

@end
